#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unordered_map>
#include <functional>
#include "log.hpp"

// using func_t = std::function<std::string(const std::string&)>;
typedef std::function<std::string(const std::string &, struct sockaddr_in client)> func_t;

static const std::string defaultip = "0.0.0.0";
static const uint16_t defaultport = 8080;

enum
{
    SOCKERROR = 1,
    BINDERROR,
    USAGEERROR
};

class UdpServer
{
public:
    UdpServer(uint16_t port = defaultport, const std::string &ip = defaultip) : _ip(ip), _port(port), _sockfd(-1)
    {
    }

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "create sockfd failed");
            exit(SOCKERROR);
        }
        LOG(INFO, "create sockfd success");

        struct sockaddr_in serveraddr;
        memset(&serveraddr, 0, sizeof(serveraddr));
        serveraddr.sin_family = AF_INET;
        serveraddr.sin_port = htons(_port);
        serveraddr.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
        if (n < 0)
        {
            LOG(FATAL, "bind socket failed");
            exit(BINDERROR);
        }
        LOG(INFO, "bind socket success");
    }

    void Adduser(const struct sockaddr_in& client, const std::string& clientip, const uint16_t& clientport)
    {
        auto it = _online_user.find(clientip);
        if(it == _online_user.end())
        {
            _online_user.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(const std::string& info, const std::string& clientip, const uint16_t& clientport)
    {
        for(const auto& user : _online_user)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            socklen_t len = sizeof(user.second);
            sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)(&user.second), len);
        }
    }

    // void start(func_t func) 
    void start() 
    {
        char buffer[64];
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        while (1)
        {
            int n = recvfrom(_sockfd, buffer, 64, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                LOG(WARNING, "recvfrom data error");
                continue;
            }
            buffer[n] = 0;
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            // 添加用户
            Adduser(client, clientip, clientport);

            // 广播
            std::string inbuffer = buffer;
            Broadcast(inbuffer, clientip, clientport);

            // std::cout << "server say# " << buffer << std::endl;
            // std::string recvdata = func(inbuffer, client);
            // sendto(_sockfd, recvdata.c_str(), recvdata.size(), 0, (struct sockaddr *)&client, len);
        }
    }

    ~UdpServer()
    {
        if (_sockfd)
            close(_sockfd);
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    std::unordered_map<std::string, struct sockaddr_in> _online_user;
};